/**
 * 通用表格管理 Composable
 * 提供统一的表格CRUD操作和状态管理
 */

import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格管理配置接口
export interface TableManagerConfig<T = any> {
  // API 函数
  fetchApi: (params: any) => Promise<{ rows: T[]; total: number }>
  addApi?: (data: T) => Promise<any>
  updateApi?: (data: T) => Promise<any>
  deleteApi?: (id: string | number) => Promise<any>
  exportApi?: (params: any) => Promise<any>
  importApi?: (file: File) => Promise<any>
  
  // 配置选项
  defaultPageSize?: number
  pageSizes?: number[]
  autoLoad?: boolean
  searchDebounce?: number
}

// 分页配置
export interface PaginationConfig {
  pageNum: number
  pageSize: number
  total: number
}

// 搜索配置
export interface SearchConfig {
  [key: string]: any
}

/**
 * 通用表格管理 Composable
 */
export function useTableManager<T = any>(config: TableManagerConfig<T>) {
  const {
    fetchApi,
    addApi,
    updateApi,
    deleteApi,
    exportApi,
    importApi,
    defaultPageSize = 10,
    pageSizes = [10, 20, 50, 100],
    autoLoad = true,
    searchDebounce = 300
  } = config

  // 状态管理
  const loading = ref(false)
  const submitLoading = ref(false)
  const tableData = ref<T[]>([])
  const selectedRows = ref<T[]>([])
  
  // 分页状态
  const pagination = reactive<PaginationConfig>({
    pageNum: 1,
    pageSize: defaultPageSize,
    total: 0
  })
  
  // 搜索状态
  const searchForm = reactive<SearchConfig>({})
  
  // 表单状态
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const formData = ref<Partial<T>>({})
  const formRules = ref<Record<string, any>>({})

  // 计算属性
  const hasSelection = computed(() => selectedRows.value.length > 0)
  const selectedCount = computed(() => selectedRows.value.length)

  // 防抖搜索
  let searchTimer: NodeJS.Timeout | null = null
  const debouncedSearch = () => {
    if (searchTimer) {
      clearTimeout(searchTimer)
    }
    searchTimer = setTimeout(() => {
      loadData()
    }, searchDebounce)
  }

  // 加载数据
  const loadData = async (params: Partial<SearchConfig> = {}) => {
    try {
      loading.value = true
      const requestParams = {
        ...searchForm,
        ...params,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      }
      
      const response = await fetchApi(requestParams)
      tableData.value = response.rows || []
      pagination.total = response.total || 0
      
      return response
    } catch (error) {
      console.error('加载数据失败:', error)
      ElMessage.error('加载数据失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = (params: Partial<SearchConfig> = {}) => {
    Object.assign(searchForm, params)
    pagination.pageNum = 1
    loadData()
  }

  // 重置搜索
  const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = ''
    })
    pagination.pageNum = 1
    loadData()
  }

  // 新增
  const handleAdd = () => {
    isEdit.value = false
    formData.value = {}
    dialogVisible.value = true
  }

  // 编辑
  const handleEdit = (row: T) => {
    isEdit.value = true
    formData.value = { ...row }
    dialogVisible.value = true
  }

  // 删除
  const handleDelete = async (row: T) => {
    try {
      await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      if (deleteApi) {
        await deleteApi((row as any).id || (row as any).userId || (row as any).roleId)
        ElMessage.success('删除成功')
        loadData()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请选择要删除的记录')
      return
    }

    try {
      await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      if (deleteApi) {
        const deletePromises = selectedRows.value.map(row => 
          deleteApi((row as any).id || (row as any).userId || (row as any).roleId)
        )
        await Promise.all(deletePromises)
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        loadData()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败')
      }
    }
  }

  // 提交表单
  const handleSubmit = async (data: Partial<T>) => {
    try {
      submitLoading.value = true
      
      if (isEdit.value && updateApi) {
        await updateApi(data as T)
        ElMessage.success('更新成功')
      } else if (!isEdit.value && addApi) {
        await addApi(data as T)
        ElMessage.success('新增成功')
      }
      
      dialogVisible.value = false
      loadData()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('操作失败')
      throw error
    } finally {
      submitLoading.value = false
    }
  }

  // 导出
  const handleExport = async () => {
    try {
      if (exportApi) {
        loading.value = true
        await exportApi({ ...searchForm, ...pagination })
        ElMessage.success('导出成功')
      }
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    } finally {
      loading.value = false
    }
  }

  // 导入
  const handleImport = async (file: File) => {
    try {
      if (importApi) {
        loading.value = true
        await importApi(file)
        ElMessage.success('导入成功')
        loadData()
      }
    } catch (error) {
      console.error('导入失败:', error)
      ElMessage.error('导入失败')
    } finally {
      loading.value = false
    }
  }

  // 刷新
  const handleRefresh = () => {
    loadData()
  }

  // 选择变化
  const handleSelectionChange = (selection: T[]) => {
    selectedRows.value = selection
  }

  // 分页变化
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageNum = 1
    loadData()
  }

  const handleCurrentChange = (page: number) => {
    pagination.pageNum = page
    loadData()
  }

  // 关闭对话框
  const handleDialogClose = () => {
    formData.value = {}
    isEdit.value = false
  }

  // 设置表单规则
  const setFormRules = (rules: Record<string, any>) => {
    formRules.value = rules
  }

  // 设置搜索表单
  const setSearchForm = (form: Partial<SearchConfig>) => {
    Object.assign(searchForm, form)
  }

  // 初始化
  if (autoLoad) {
    loadData()
  }

  return {
    // 状态
    loading,
    submitLoading,
    tableData,
    selectedRows,
    pagination,
    searchForm,
    dialogVisible,
    isEdit,
    formData,
    formRules,
    
    // 计算属性
    hasSelection,
    selectedCount,
    
    // 方法
    loadData,
    handleSearch,
    handleReset,
    handleAdd,
    handleEdit,
    handleDelete,
    handleBatchDelete,
    handleSubmit,
    handleExport,
    handleImport,
    handleRefresh,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    handleDialogClose,
    setFormRules,
    setSearchForm,
    debouncedSearch
  }
}

/**
 * 用户管理专用 Composable
 */
export function useUserTableManager() {
  return useTableManager({
    fetchApi: async (params) => {
      // 这里应该调用实际的用户API
      console.log('用户查询参数:', params)
      return { rows: [], total: 0 }
    },
    addApi: async (data) => {
      console.log('新增用户:', data)
    },
    updateApi: async (data) => {
      console.log('更新用户:', data)
    },
    deleteApi: async (id) => {
      console.log('删除用户:', id)
    }
  })
}

/**
 * 角色管理专用 Composable
 */
export function useRoleTableManager() {
  return useTableManager({
    fetchApi: async (params) => {
      console.log('角色查询参数:', params)
      return { rows: [], total: 0 }
    },
    addApi: async (data) => {
      console.log('新增角色:', data)
    },
    updateApi: async (data) => {
      console.log('更新角色:', data)
    },
    deleteApi: async (id) => {
      console.log('删除角色:', id)
    }
  })
}

/**
 * 菜单管理专用 Composable
 */
export function useMenuTableManager() {
  return useTableManager({
    fetchApi: async (params) => {
      console.log('菜单查询参数:', params)
      return { rows: [], total: 0 }
    },
    addApi: async (data) => {
      console.log('新增菜单:', data)
    },
    updateApi: async (data) => {
      console.log('更新菜单:', data)
    },
    deleteApi: async (id) => {
      console.log('删除菜单:', id)
    }
  })
}

/**
 * 部门管理专用 Composable
 */
export function useDeptTableManager() {
  return useTableManager({
    fetchApi: async (params) => {
      console.log('部门查询参数:', params)
      return { rows: [], total: 0 }
    },
    addApi: async (data) => {
      console.log('新增部门:', data)
    },
    updateApi: async (data) => {
      console.log('更新部门:', data)
    },
    deleteApi: async (id) => {
      console.log('删除部门:', id)
    }
  })
}
